package com.fastloan.mgt.product.basics.service.impl;

import com.fastloan.common.BasicServiceImpl;
import com.fastloan.mgt.product.basics.model.Product;
import com.fastloan.mgt.product.basics.model.ProductFile;
import com.fastloan.mgt.product.basics.service.ProductFileService;
import com.fastloan.mgt.product.basics.service.ProductService;
import com.kawins.supers.file.IFileManager;
import com.kawins.supers.file.core.FileLoadBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

import static com.fastloan.mgt.product.enums.ProductEnum.PUBLISHED;

/**
 * @author admins
 */
@Service
public class ProductFileServiceImpl extends BasicServiceImpl<ProductFile> implements ProductFileService {

    @Autowired
    private IFileManager fileManager;

    @Autowired
    private ProductService productService;

    @Override
    @Transactional
    public List<FileLoadBean> uploadProductFile(String productId, Integer fileType, MultipartFile[] file) {
        List<FileLoadBean> fileLoadBeanList = fileManager.upload(file);
        if (fileLoadBeanList != null && !fileLoadBeanList.isEmpty()) {
            deleteProductFile(productId, fileType);
            fileLoadBeanList.forEach(fileLoadBean -> {
                ProductFile productFile1 = new ProductFile();
                productFile1.setType(fileType);
                productFile1.setProductId(productId);
                productFile1.setFileId(fileLoadBean.getFileId().toString());
                insert(productFile1);
            });
            if (fileType.equals(PUBLISHED.getType())) {
                Product product = productService.selectByPrimaryKey(productId);
                productService.updateLogoUrl(fileLoadBeanList, product);
            }
        }

        return fileLoadBeanList;
    }

    @Override
    @Transactional
    public void deleteProductFile(String productId, Integer fileType) {
        ProductFile productFile = new ProductFile();
        productFile.setProductId(productId);
        productFile.setType(fileType);
        List<ProductFile> productFiles = select(productFile);
        if (productFiles != null && !productFiles.isEmpty()) {
            productFiles.stream().map(ProductFile::getFileId)
                    .forEach(fileId -> {
                        fileManager.delete(fileId);
                        deleteByPrimaryKey(fileId);
                    });
        }
    }
}
